package com.appkubes.portal.admin.facility.util;

import com.appkubes.portal.admin.application.app.menu.entity.dto.PortalAppMenuDTO;

import java.util.ArrayList;
import java.util.List;

public class MenuTree {
    private List<PortalAppMenuDTO> menuList = new ArrayList<>();
    public MenuTree(List<PortalAppMenuDTO> menuList) {
        this.menuList=menuList;
    }

    //建立树形结构
    public List<PortalAppMenuDTO> builTree(){
        List<PortalAppMenuDTO> treeMenus =new  ArrayList<>();
        for(PortalAppMenuDTO menuNode : getRootNode()) {
            menuNode=buildChilTree(menuNode);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    //递归，建立子树形结构
    private PortalAppMenuDTO buildChilTree(PortalAppMenuDTO pNode){
        List<PortalAppMenuDTO> chilMenus =new  ArrayList<>();
        for(PortalAppMenuDTO menuNode : menuList) {
            if(menuNode.getParentMenuKey().equals(pNode.getMenuKey())) {
                chilMenus.add(buildChilTree(menuNode));
            }
        }
        pNode.setChildren(chilMenus);
        return pNode;
    }

    //获取根节点
    private List<PortalAppMenuDTO> getRootNode() {
        List<PortalAppMenuDTO> rootMenuLists =new  ArrayList<>();
        for(PortalAppMenuDTO menuNode : menuList) {
            if(menuNode.getMenuLevel().equals(0)) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }
}
